﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using WLFramework.Data.Linq;
using WLFramework.Json;
using WLFramework.Mapping;
using WLFramework.Web;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// setRolePositions 的摘要说明
    /// </summary>
    public class setRolePositions : AjaxHttpHandler
    {
        private class JsonData
        {
            public int r_id { get; set; }
            public string p_ids { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            string data = context.GetValueByName<string>("data");
            if (data != null && data.Trim().Length != 0)
            {
                throw new Exception("输入参数错误!");
            }

            var input = JSON.Instance.ToObject<Dictionary<string, object>>(data);

            int r_id = Convert.ToInt32(input["r_id"]);
            int[] p_ids = Array.ConvertAll<object, int>((object[])input["p_ids"], Convert.ToInt32);

            using (CommandHelper db = new CommandHelper(CommandMethod.Write))
            {
                db.Context.BeginTransaction();
                if (db.Context.sys_Roles.Where(k => k.R_ID == r_id).Count() != 1)
                    throw new Exception("输入参数错误!");

                db.Context.sys_PostRoles.Where(k => k.R_ID == r_id)
                          .Delete();

                if (p_ids != null && p_ids.Length != 0)
                {
                    List<sys_PostRoles> rows = new List<sys_PostRoles>();
                    foreach (var i in p_ids)
                    {
                        rows.Add(new sys_PostRoles()
                        {
                            P_ID = i,
                            R_ID = r_id,
                            R_State = 1
                        });
                    }

                    db.Context.InsertBatch(rows);
                }

                db.Context.CommitTransaction();
            }

            context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
        }
    }
}